<template>
  <el-card class="preset-selector-card" shadow="never">
    <template #header>
      <div class="card-header">
        <el-icon class="header-icon"><MagicStick /></el-icon>
        <span class="header-title">选择应用</span>
        <el-text type="info" size="small">选择应用后可自动筛选相关配置</el-text>
      </div>
    </template>

    <el-form :inline="true" class="preset-form">
      <el-form-item label="应用">
        <el-select
          v-model="selectedApplication"
          placeholder="请选择应用"
          clearable
          @change="handleApplicationChange"
          style="width: 300px"
        >
          <el-option
            v-for="app in applications"
            :key="app.id"
            :label="app.name"
            :value="app.id"
          >
            <span>{{ app.name }}</span>
            <el-text v-if="app.description" type="info" size="small" style="margin-left: 8px">{{ app.description }}</el-text>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { MagicStick } from '@element-plus/icons-vue'
import {
  getApplications,
} from '@/api/configPreset'

const props = defineProps({
  defaultApplicationId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['application-change'])

const selectedApplication = ref(null)
const applications = ref([])

// 加载应用列表
const loadApplications = async () => {
  try {
    const res = await getApplications({ active_only: true })
    applications.value = res.items

    // 如果传入了默认应用ID，设置默认值
    if (props.defaultApplicationId) {
      selectedApplication.value = props.defaultApplicationId
    }
  } catch (error) {
    console.error('加载应用列表失败:', error)
    ElMessage.error('加载应用列表失败')
  }
}

// 处理应用选择变化
const handleApplicationChange = (applicationId) => {
  emit('application-change', applicationId)
  if (applicationId) {
    const app = applications.value.find(a => a.id === applicationId)
    if (app) {
      ElMessage.success(`已选择应用: ${app.name}`)
    }
  }
}

// 监听 defaultApplicationId 变化
watch(() => props.defaultApplicationId, (newValue) => {
  if (newValue) {
    selectedApplication.value = newValue
  }
})

onMounted(() => {
  loadApplications()
})
</script>

<style scoped lang="scss">
.preset-selector-card {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;

  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;

    .header-icon {
      font-size: 18px;
      color: #409eff;
    }

    .header-title {
      font-weight: 600;
      font-size: 16px;
      color: #303133;
      margin-right: 12px;
    }
  }

  .preset-form {
    margin: 0;

    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }
}
</style>
